<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>SoundWave - 音乐库</title>

    <link rel="shortcut icon" href="#"/>

    <!-- 外部资源加载 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.slim.min.js"></script>

    <style type="text/css">
        /* 保持原有样式不变 */
        body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #121a2e 0%, #1e3163 100%);
            color: #f0f0f0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            position: relative;
            overflow-x: hidden;
        }

        .bg-pattern {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: radial-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px);
            background-size: 30px 30px;
            z-index: 0;
            opacity: 0.3;
        }

        .floating-note {
            position: absolute;
            color: rgba(255, 255, 255, 0.05);
            font-size: 2rem;
            animation: float 20s infinite ease-in-out;
            will-change: transform, opacity;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0) rotate(0deg); opacity: 0.05; }
            50% { transform: translateY(-60px) rotate(10deg); opacity: 0.15; }
        }

        .container {
            position: relative;
            z-index: 1;
            padding: 30px 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .page-header {
            text-align: center;
            margin-bottom: 40px;
            position: relative;
        }

        .page-title {
            font-size: 2.5rem;
            font-weight: 700;
            background: linear-gradient(90deg, #3498db, #9b59b6);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            display: inline-flex;
            align-items: center;
            gap: 15px;
        }

        .page-title i {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        .page-subtitle {
            color: rgba(255, 255, 255, 0.6);
            margin-top: 10px;
            font-size: 1rem;
        }

        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .search-form {
            display: flex;
            gap: 10px;
            align-items: center;
            flex: 1;
            max-width: 500px;
        }

        .search-input {
            flex: 1;
            padding: 12px 20px;
            background: rgba(255, 255, 255, 0.07);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 30px;
            color: #fff;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #9b59b6;
            box-shadow: 0 0 0 3px rgba(155, 89, 182, 0.2);
            background: rgba(255, 255, 255, 0.1);
        }

        .search-input::placeholder {
            color: rgba(255, 255, 255, 0.4);
        }

        .btn {
            padding: 10px 20px;
            border-radius: 30px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            position: relative;
            overflow: hidden;
        }

        /* 播放按钮特殊样式 - 与收藏页保持一致大小 */
        .play-btn {
            padding: 6px 12px;
            font-size: 0.9rem;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: all 0.6s ease;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: linear-gradient(90deg, #3498db, #2980b9);
            color: white;
        }

        .btn-primary:hover {
            background: linear-gradient(90deg, #2980b9, #3498db);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
            color: white;
        }

        .btn-secondary {
            background: linear-gradient(90deg, #9b59b6, #8e44ad);
            color: white;
        }

        .btn-secondary:hover {
            background: linear-gradient(90deg, #8e44ad, #9b59b6);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(155, 89, 182, 0.3);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(90deg, #e74c3c, #c0392b);
            color: white;
        }

        .btn-danger:hover {
            background: linear-gradient(90deg, #c0392b, #e74c3c);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
            color: white;
        }

        .music-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .music-table th,
        .music-table td {
            padding: 15px 20px;
            text-align: center;
            vertical-align: middle;
            transition: all 0.3s ease;
        }

        .music-table th {
            background: rgba(255, 255, 255, 0.07);
            font-weight: 600;
            color: #bbb;
            position: relative;
        }

        .music-table th:after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        }

        .music-table tbody tr {
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }

        .music-table tbody tr:hover {
            background: rgba(255, 255, 255, 0.05);
            transform: translateX(5px);
        }

        .music-table td:first-child {
            width: 80px;
        }

        .music-title {
            display: flex;
            align-items: center;
            gap: 12px;
            justify-content: center;
        }

        .music-title i {
            color: #9b59b6;
            opacity: 0.7;
        }

        input[type="checkbox"] {
            width: 18px;
            height: 18px;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            accent-color: #9b59b6;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        input[type="checkbox"]:checked {
            box-shadow: 0 0 0 2px rgba(155, 89, 182, 0.3);
        }

        /* 播放栏样式优化 - 与代码1保持一致 */
        .player-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 320px;
            background: rgba(25, 35, 65, 0.9);
            backdrop-filter: blur(15px);
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: all 0.3s ease;
            z-index: 100;
            overflow: hidden;
        }

        .player-container:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
        }

        /* 缩小状态的样式 - 改为纯圆形图标 */
        .player-container.minimized {
            width: 70px;
            height: 70px;
            padding: 0;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            position: relative; /* 确保相对定位 */
        }

        .player-container.minimized .now-playing,
        .player-container.minimized .progress-container,
        .player-container.minimized .minimize-btn,
        .player-container.minimized #stopBtn,
        .player-container.minimized .player-controls {
            display: none;
        }

        .player-container.minimized .minimized-icon {
            display: flex !important;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            font-size: 24px;
            color: rgba(255, 255, 255, 0.9);
            animation: pulse 2s infinite;
            position: absolute; /* 绝对定位确保居中 */
            top: 0;
            left: 0;
        }

        .player-container.minimized .minimized-icon::before {
            content: "";
            position: absolute;
            top: 5px;
            left: 5px;
            right: 5px;
            bottom: 5px;
            border-radius: 50%;
            background: linear-gradient(135deg, #3498db, #9b59b6);
            z-index: -1;
        }

        .now-playing {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.7);
            margin-bottom: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .player-controls {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin: 10px 0;
        }

        .control-btn {
            background: none;
            border: none;
            color: #fff;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            border-radius: 50%;
        }

        .control-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .play-pause-btn {
            width: 50px;
            height: 50px;
            background: linear-gradient(90deg, #3498db, #9b59b6);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .play-pause-btn:hover {
            transform: scale(1.05);
            background: linear-gradient(90deg, #2980b9, #8e44ad);
        }

        /* 最小化按钮样式 */
        .minimize-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: none;
            border: none;
            color: rgba(255, 255, 255, 0.6);
            cursor: pointer;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.2s ease;
            z-index: 10;
        }

        .minimize-btn:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #fff;
        }

        /* 缩小状态显示的图标 */
        .minimized-icon {
            display: none;
        }

        .progress-container {
            width: 100%;
            margin: 10px 0;
        }

        .progress-info {
            display: flex;
            justify-content: space-between;
            font-size: 0.8rem;
            color: rgba(255, 255, 255, 0.6);
            margin-bottom: 5px;
        }

        .progress-bar {
            width: 100%;
            height: 5px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 5px;
            position: relative;
            cursor: pointer;
            z-index: 1;
        }

        .progress-fill {
            position: absolute;
            height: 100%;
            background: linear-gradient(90deg, #3498db, #9b59b6);
            border-radius: 5px;
            width: 0%;
            transition: width 0.1s linear;
            z-index: 2;
        }

        .progress-handle {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            background: white;
            border-radius: 50%;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
            display: none;
            z-index: 3;
        }

        .progress-bar:hover .progress-handle {
            display: block;
        }

        .audio-wave {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 60px;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            gap: 2px;
            z-index: 0;
            opacity: 0.3;
        }

        .wave-bar {
            width: 3px;
            background: linear-gradient(to top, #3498db, #9b59b6);
            border-radius: 2px;
            animation: wave 1.5s infinite ease-in-out;
            will-change: height;
        }

        @keyframes wave {
            0%, 100% { height: 5px; }
            50% { height: calc(5px + var(--random-height, 30px)); }
        }

        @media (max-width: 768px) {
            .action-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .search-form {
                max-width: 100%;
            }

            .btn-group {
                display: flex;
                gap: 10px;
                flex-wrap: wrap;
            }

            .btn {
                flex: 1;
                min-width: 120px;
                justify-content: center;
            }

            .music-table th:nth-child(5),
            .music-table td:nth-child(5) {
                display: none;
            }

            .player-container {
                width: calc(100% - 40px);
                left: 20px;
                right: 20px;
            }

            /* 响应式调整：缩小状态 */
            .player-container.minimized {
                width: 60px;
                height: 60px;
                left: auto;
                right: 20px;
            }
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
            color: rgba(255, 255, 255, 0.6);
        }

        .loading i {
            font-size: 2rem;
            animation: spin 1.5s infinite linear;
            margin-bottom: 15px;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            background: rgba(25, 35, 65, 0.9);
            color: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            transform: translateX(120%);
            transition: transform 0.3s ease;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .toast.show {
            transform: translateX(0);
        }

        .toast-success {
            border-left: 4px solid #2ecc71;
        }

        .toast-error {
            border-left: 4px solid #e74c3c;
        }

        .playing-row {
            background: rgba(52, 152, 219, 0.15);
        }
    </style>

    <script type="text/javascript">
        // 全局变量 - 与代码1保持一致
        let currentAudio = null;
        let isPlaying = false;
        let progressInterval = null;
        let currentMusicId = null;
        let musicCache = new Map(); // 缓存已加载的音乐信息
        let isPlayerMinimized = false; // 标记播放栏是否处于缩小状态

        // 预定义DOM选择器和工具函数 - 与代码1保持一致
        const $ = document.querySelector.bind(document);
        const $$ = document.querySelectorAll.bind(document);

        // 核心代码实现
        document.addEventListener('DOMContentLoaded', function() {
            // 创建背景装饰
            createBackgroundElements();

            // 创建提示消息元素
            createToastElement();

            // 加载音乐列表
            load();

            // 绑定搜索按钮事件
            document.getElementById('submit1').addEventListener('click', function() {
                const name = document.getElementById('exampleInputName2').value;
                load(name);
            });

            // 绑定删除选中按钮事件
            document.getElementById('delete').addEventListener('click', deleteSelected);

            // 绑定回车键搜索
            document.getElementById('exampleInputName2').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    const name = this.value;
                    load(name);
                }
            });

            // 绑定播放/暂停按钮事件 - 与代码1保持一致
            document.getElementById('playPauseBtn').addEventListener('click', function(e) {
                // 防止事件冒泡到容器
                e.stopPropagation();
                togglePlayPause();
            });

            // 绑定最小化按钮事件 - 与代码1保持一致
            document.getElementById('minimizeBtn').addEventListener('click', function(e) {
                // 防止事件冒泡到容器
                e.stopPropagation();
                toggleMinimizePlayer();
            });

            // 绑定进度条点击事件 - 与代码1保持一致
            const progressBar = document.querySelector('.progress-bar');
            progressBar.addEventListener('click', function(e) {
                e.stopPropagation(); // 防止事件冒泡
                seekAudio(e);
            });

            // 添加进度条拖动功能 - 与代码1保持一致
            let isDragging = false;
            progressBar.addEventListener('mousedown', function(e) {
                e.stopPropagation(); // 防止事件冒泡
                isDragging = true;
                seekAudio(e);
            });

            document.addEventListener('mousemove', function(e) {
                if (isDragging && currentAudio) {
                    seekAudio(e);
                }
            });

            document.addEventListener('mouseup', function() {
                isDragging = false;
            });

            // 绑定停止按钮事件，防止事件冒泡 - 与代码1保持一致
            document.getElementById('stopBtn').addEventListener('click', function(e) {
                e.stopPropagation();
                stopCurrentAudio();
            });

            // 绑定播放栏容器点击事件 - 实现缩小状态下点击放大 - 与代码1保持一致
            const playerContainer = document.querySelector('.player-container');
            playerContainer.addEventListener('click', function() {
                if (isPlayerMinimized) {
                    // 当处于缩小状态时，点击容器任意位置都放大
                    toggleMinimizePlayer();
                }
            });
        });

        // 切换播放栏大小的函数 - 与代码1保持一致
        function toggleMinimizePlayer() {
            const playerContainer = document.querySelector('.player-container');
            const minimizeIcon = document.querySelector('.minimize-btn i');

            isPlayerMinimized = !isPlayerMinimized;

            if (isPlayerMinimized) {
                playerContainer.classList.add('minimized');
                minimizeIcon.className = 'fas fa-expand-alt'; // 切换图标为放大
            } else {
                playerContainer.classList.remove('minimized');
                minimizeIcon.className = 'fas fa-compress'; // 切换图标为缩小
            }
        }

        // 创建背景装饰元素
        function createBackgroundElements() {
            // 创建音符装饰
            const noteTypes = ['fa-music', 'fa-volume-up', 'fa-compact-disc', 'fa-microphone'];
            const body = document.body;

            // 分批创建音符，避免一次性大量DOM操作
            let count = 0;
            const totalNotes = 6;

            const createNote = () => {
                if (count < totalNotes) {
                    const note = document.createElement('i');
                    const type = noteTypes[Math.floor(Math.random() * noteTypes.length)];
                    note.className = `fas ${type} floating-note`;
                    note.style.left = `${Math.random() * 100}%`;
                    note.style.top = `${Math.random() * 100}%`;
                    note.style.animationDelay = `${Math.random() * 5}s`;
                    note.style.fontSize = `${1 + Math.random() * 2}rem`;
                    note.style.transform = `rotate(${Math.random() * 360}deg)`;
                    body.appendChild(note);

                    count++;
                    setTimeout(createNote, 100);
                } else {
                    // 创建音频波形
                    createWaveElements();
                }
            };

            createNote();
        }

        // 创建波形元素
        function createWaveElements() {
            const waveContainer = document.createElement('div');
            waveContainer.className = 'audio-wave';
            document.body.appendChild(waveContainer);

            let barCount = 0;
            const totalBars = 40;

            const createBar = () => {
                if (barCount < totalBars) {
                    const bar = document.createElement('div');
                    bar.className = 'wave-bar';
                    bar.style.setProperty('--random-height', `${Math.random() * 40 + 10}px`);
                    bar.style.animationDelay = `${Math.random() * 1.5}s`;
                    waveContainer.appendChild(bar);

                    barCount++;
                    setTimeout(createBar, 10);
                }
            };

            createBar();
        }

        // 创建提示消息元素 - 与代码1保持一致
        function createToastElement() {
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.id = 'toast-message';
            document.body.appendChild(toast);
        }

        // 显示提示消息 - 与代码1保持一致
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast-message');
            // 如果有正在显示的提示，先移除
            toast.classList.remove('show', 'toast-success', 'toast-error');

            toast.classList.add(`toast-${type}`);
            toast.innerHTML = type === 'success' ?
                `<i class="fas fa-check-circle"></i> ${message}` :
                `<i class="fas fa-exclamation-circle"></i> ${message}`;

            // 使用setTimeout确保样式变更被浏览器捕获
            setTimeout(() => {
                toast.classList.add('show');
            }, 10);

            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // 加载音乐列表 - 保留原有功能，优化缓存机制
        function load(musicName) {
            // 显示加载状态
            const infoContainer = document.getElementById('info');
            infoContainer.innerHTML = '<tr><td colspan="5" class="loading"><i class="fas fa-spinner fa-spin"></i><div>加载音乐中...</div></td></tr>';

            // 检查缓存
            const cacheKey = musicName || 'all';
            if (musicCache.has(cacheKey)) {
                renderMusicList(musicCache.get(cacheKey));
                return;
            }

            const xhr = new XMLHttpRequest();
            let url = "/music/findmusic";

            if (musicName) {
                url += "?musicName=" + encodeURIComponent(musicName);
            }

            xhr.open("GET", url, true);
            xhr.responseType = "json";

            // 设置超时时间
            xhr.timeout = 10000;

            xhr.onload = function() {
                if (xhr.status === 200) {
                    const obj = xhr.response;
                    console.log(obj);

                    if (obj && obj.data) {
                        // 存入缓存
                        musicCache.set(cacheKey, obj.data);
                        renderMusicList(obj.data);
                    } else {
                        infoContainer.innerHTML = '<tr><td colspan="5" style="padding: 40px; color: rgba(255,255,255,0.5);">加载失败</td></tr>';
                    }
                } else {
                    infoContainer.innerHTML = '<tr><td colspan="5" style="padding: 40px; color: rgba(255,255,255,0.5);">请求失败</td></tr>';
                }
            };

            xhr.ontimeout = function() {
                infoContainer.innerHTML = '<tr><td colspan="5" style="padding: 40px; color: rgba(255,255,255,0.5);">请求超时</td></tr>';
            };

            xhr.onerror = function() {
                infoContainer.innerHTML = '<tr><td colspan="5" style="padding: 40px; color: rgba(255,255,255,0.5);">网络错误</td></tr>';
            };

            xhr.send();
        }

        // 渲染音乐列表 - 修改播放按钮样式和调用函数
        function renderMusicList(data) {
            const infoContainer = document.getElementById('info');
            let html = '';

            if (data.length === 0) {
                html = '<tr><td colspan="5" style="padding: 40px; color: rgba(255,255,255,0.5);">未找到相关音乐</td></tr>';
            } else {
                for (let i = 0; i < data.length; i++) {
                    // 处理音乐URL
                    const rawPath = data[i].url.split('=')[1];
                    const musicUrl = "/music/get?path=" + rawPath + ".mp3";

                    // 判断是否是当前播放的音乐
                    const isCurrentPlaying = currentMusicId === data[i].id;

                    // 错开一点时间添加，避免一次性渲染过多DOM - 与代码1保持一致
                    setTimeout(() => {
                        const row = document.getElementById(`row-${data[i].id}`);
                        if (row) row.style.opacity = '1';
                    }, i * 50);

                    html += `<tr id="row-${data[i].id}" ${isCurrentPlaying ? 'class="playing-row"' : ''} style="opacity: 0; transition: opacity 0.3s ease;">`;
                    html += `<th><input id="${data[i].id}" type="checkbox"></th>`;
                    html += `<td><div class="music-title"><i class="fas fa-music"></i>${data[i].title}</div></td>`;
                    html += `<td>${data[i].singer}</td>`;
                    // 修改播放按钮样式和调用函数，与代码1保持一致
                    html += `<td><button class="btn btn-primary play-btn" onclick="playMusic('${musicUrl}', ${data[i].id}, '${data[i].title}', '${data[i].singer}')">
                                <i class="fas ${isCurrentPlaying && isPlaying ? 'fa-pause' : 'fa-play'}"></i>
                                ${isCurrentPlaying && isPlaying ? '暂停' : '播放'}
                            </button></td>`;
                    html += `<td>
                                <button class="btn btn-danger" onclick="deleteInfo(${data[i].id})"><i class="fas fa-trash"></i>删除</button>
                                <button class="btn btn-secondary" onclick="loveInfo(${data[i].id})"><i class="fas fa-heart"></i>喜欢</button>
                            </td>`;
                    html += "</tr>";
                }
            }

            infoContainer.innerHTML = html;
        }

        // 播放/切换歌曲 - 重命名为playMusic，参数与代码1保持一致
        function playMusic(url, musicId, title, singer) {
            // 如果点击的是当前正在播放的歌曲，则切换播放/暂停状态
            if (currentMusicId === musicId) {
                togglePlayPause();
                return;
            }

            // 停止当前播放的音频
            stopCurrentAudio();

            // 更新当前播放ID
            currentMusicId = musicId;

            // 更新正在播放信息，同时显示歌曲名和歌手 - 与代码1保持一致
            document.querySelector('.now-playing').textContent = `正在播放: ${title} - ${singer}`;

            // 创建新的音频对象
            currentAudio = new Audio(url);

            // 监听元数据加载完成事件（获取时长）
            currentAudio.onloadedmetadata = function() {
                document.querySelector('.duration').textContent = formatTime(currentAudio.duration);
            };

            // 音频可以播放时自动播放
            currentAudio.oncanplaythrough = function() {
                playAudio();
            };

            // 音频结束时的处理
            currentAudio.onended = function() {
                stopAudio();
            };

            // 显示播放器并确保它处于正常大小状态 - 与代码1保持一致
            const player = document.querySelector('.player-container');
            player.style.display = 'block';
            if (isPlayerMinimized) {
                toggleMinimizePlayer(); // 如果处于缩小状态，则恢复正常大小
            }

            // 更新表格中按钮状态
            updatePlayButtons();
        }

        // 播放音频 - 与代码1保持一致
        function playAudio() {
            if (!currentAudio) return;

            currentAudio.play().then(() => {
                isPlaying = true;
                // 更新播放按钮图标
                document.getElementById('playPauseIcon').className = 'fas fa-pause';
                // 启动进度更新定时器
                startProgressUpdate();
                // 更新表格中按钮状态
                updatePlayButtons();
            }).catch(error => {
                console.error("播放失败:", error);
                showToast("播放失败，请重试", "error");
            });
        }

        // 暂停音频 - 与代码1保持一致
        function pauseAudio() {
            if (!currentAudio) return;

            currentAudio.pause();
            isPlaying = false;
            // 更新播放按钮图标
            document.getElementById('playPauseIcon').className = 'fas fa-play';
            // 停止进度更新定时器
            stopProgressUpdate();
            // 更新表格中按钮状态
            updatePlayButtons();
        }

        // 停止当前音频 - 与代码1保持一致
        function stopCurrentAudio() {
            if (currentAudio) {
                pauseAudio();
                currentAudio.currentTime = 0;
                // 重置进度条
                updateProgress(0);
                document.querySelector('.current-time').textContent = "00:00";
            }
        }

        // 切换播放/暂停状态 - 与代码1保持一致
        function togglePlayPause() {
            if (!currentAudio) return;

            if (isPlaying) {
                pauseAudio();
            } else {
                playAudio();
            }
        }

        // 开始更新进度条 - 与代码1保持一致
        function startProgressUpdate() {
            // 先清除可能存在的定时器
            stopProgressUpdate();

            // 创建新的定时器
            progressInterval = setInterval(() => {
                if (currentAudio && !isNaN(currentAudio.duration) && currentAudio.duration > 0) {
                    const progress = (currentAudio.currentTime / currentAudio.duration) * 100;
                    updateProgress(progress);
                    document.querySelector('.current-time').textContent = formatTime(currentAudio.currentTime);
                }
            }, 100);
        }

        // 停止更新进度条 - 与代码1保持一致
        function stopProgressUpdate() {
            if (progressInterval) {
                clearInterval(progressInterval);
                progressInterval = null;
            }
        }

        // 更新进度条显示 - 与代码1保持一致
        function updateProgress(percent) {
            const progressFill = document.querySelector('.progress-fill');
            const progressHandle = document.querySelector('.progress-handle');

            progressFill.style.width = `${percent}%`;
            progressHandle.style.left = `${percent}%`;
        }

        // 调整音频进度 - 与代码1保持一致
        function seekAudio(e) {
            // 验证音频是否准备好
            if (!currentAudio || isNaN(currentAudio.duration) || currentAudio.duration <= 0) {
                return;
            }

            const progressBar = document.querySelector('.progress-bar');
            const rect = progressBar.getBoundingClientRect();

            // 确保我们获取到了正确的宽度
            if (rect.width <= 0) {
                console.error("进度条宽度为0，无法计算位置");
                return;
            }

            // 计算点击位置在进度条中的百分比
            let pos = (e.clientX - rect.left) / rect.width;
            // 限制在0-1范围内
            pos = Math.max(0, Math.min(1, pos));

            const seekTime = pos * currentAudio.duration;

            // 先暂停再设置.currentTime，然后根据需要恢复播放状态
            const wasPlaying = isPlaying;
            if (wasPlaying) {
                pauseAudio();
            }

            // 设置音频进度
            currentAudio.currentTime = seekTime;

            // 更新UI
            updateProgress(pos * 100);
            document.querySelector('.current-time').textContent = formatTime(seekTime);

            // 如果之前是播放状态，继续播放
            if (wasPlaying) {
                // 使用setTimeout确保.currentTime已更新
                setTimeout(playAudio, 100);
            }
        }

        // 格式化时间（秒 -> mm:ss） - 与代码1保持一致
        function formatTime(seconds) {
            if (isNaN(seconds)) return "00:00";

            const mins = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);

            return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }

        // 更新表格中的播放按钮状态 - 与代码1保持一致
        function updatePlayButtons() {
            const rows = document.querySelectorAll('#info tr');
            rows.forEach(row => {
                const playBtn = row.querySelector('.btn-primary.play-btn');
                if (playBtn && row.id.startsWith('row-')) {
                    // 提取音乐ID
                    const musicId = parseInt(row.id.split('-')[1]);
                    // 检查当前行是否是正在播放的音乐
                    const isCurrentRow = musicId === currentMusicId;

                    if (isCurrentRow) {
                        row.classList.add('playing-row');
                        if (isPlaying) {
                            playBtn.innerHTML = '<i class="fas fa-pause"></i>暂停';
                        } else {
                            playBtn.innerHTML = '<i class="fas fa-play"></i>播放';
                        }
                    } else {
                        row.classList.remove('playing-row');
                        playBtn.innerHTML = '<i class="fas fa-play"></i>播放';
                    }
                }
            });
        }

        // 停止音频（播放结束时调用） - 与代码1保持一致
        function stopAudio() {
            pauseAudio();
            currentAudio.currentTime = 0;
            updateProgress(0);
            document.querySelector('.current-time').textContent = "00:00";
        }

        // 删除单个歌曲 - 保留原有功能
        function deleteInfo(id) {
            // 如果删除的是当前正在播放的歌曲，先停止播放
            if (currentMusicId == id) {
                stopCurrentAudio();
                currentMusicId = null;
                document.querySelector('.now-playing').textContent = "正在播放: 暂无歌曲";
            }

            if (confirm("确定要删除这首歌吗？")) {
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "/music/delete", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.responseType = "json";

                // 设置超时
                xhr.timeout = 5000;

                xhr.onload = function() {
                    if (xhr.status === 200) {
                        const val = xhr.response;
                        if (val && val.data === true) {
                            showToast("删除成功！");
                            // 清除缓存，确保重新加载最新数据
                            musicCache.clear();
                            // 重新加载列表
                            const searchTerm = document.getElementById('exampleInputName2').value;
                            load(searchTerm);
                        } else {
                            showToast("删除失败！", "error");
                        }
                    } else {
                        showToast("删除请求失败", "error");
                    }
                };

                xhr.ontimeout = function() {
                    showToast("删除超时", "error");
                };

                xhr.onerror = function() {
                    showToast("网络错误，删除失败", "error");
                };

                xhr.send(`id=${id}`);
            }
        }

        // 删除选中歌曲 - 修复批量删除功能
        function deleteSelected() {
            // 获取所有选中的复选框
            const checkboxes = document.querySelectorAll("input[type='checkbox']:checked");
            if (checkboxes.length === 0) {
                showToast("请先选择要删除的歌曲", "error");
                return;
            }

            // 收集选中的ID
            const ids = Array.from(checkboxes).map(cb => {
                const id = cb.id;
                // 如果删除的是当前正在播放的歌曲，先停止播放
                if (currentMusicId == id) {
                    stopCurrentAudio();
                    currentMusicId = null;
                    document.querySelector('.now-playing').textContent = "正在播放: 暂无歌曲";
                }
                return id;
            });

            if (confirm(`确定要删除选中的 ${checkboxes.length} 首歌曲吗？`)) {
                // 使用XMLHttpRequest发送请求
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "/music/deleteSel", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.responseType = "json";

                // 设置超时
                xhr.timeout = 5000;

                xhr.onload = function() {
                    if (xhr.status === 200) {
                        const obj = xhr.response;
                        if (obj && obj.data === true) {
                            showToast(`成功删除 ${checkboxes.length} 首歌曲`);
                            // 清除缓存
                            musicCache.clear();
                            // 重新加载列表
                            const searchTerm = document.getElementById('exampleInputName2').value;
                            load(searchTerm);
                        } else {
                            showToast("删除失败！", "error");
                        }
                    } else {
                        showToast("删除请求失败", "error");
                    }
                };

                xhr.ontimeout = function() {
                    showToast("删除超时", "error");
                };

                xhr.onerror = function() {
                    showToast("网络错误，删除失败", "error");
                };

                // 构建正确的表单数据格式：id[]=1&id[]=2&id[]=3...
                let formData = '';
                ids.forEach((id, index) => {
                    if (index > 0) {
                        formData += '&';
                    }
                    formData += `id[]=${encodeURIComponent(id)}`;
                });

                xhr.send(formData);
            }
        }

        // 收藏歌曲 - 保留原有功能
        function loveInfo(id) {
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "/lovemusic/likeMusic", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.responseType = "json";

            xhr.timeout = 5000;

            xhr.onload = function() {
                if (xhr.status === 200) {
                    const val = xhr.response;
                    if (val && val.data === true) {
                        showToast("收藏成功！");
                    } else {
                        showToast("收藏失败！", "error");
                    }
                } else {
                    showToast("收藏请求失败", "error");
                }
            };

            xhr.ontimeout = function() {
                showToast("收藏超时", "error");
            };

            xhr.onerror = function() {
                showToast("网络错误，收藏失败", "error");
            };

            xhr.send(`id=${id}`);
        }
    </script>
</head>

<body>
<div class="bg-pattern"></div>

<div class="container">
    <div class="page-header">
        <h1 class="page-title">
            <i class="fas fa-music"></i>
            SoundWave 音乐库
        </h1>
        <p class="page-subtitle">探索、聆听、收藏你喜爱的音乐</p>
    </div>

    <div class="action-bar">
        <form class="search-form">
            <input name="name" type="text" class="search-input" id="exampleInputName2" placeholder="搜索歌曲...">
            <button id="submit1" type="button" class="btn btn-primary">
                <i class="fas fa-search"></i>搜索
            </button>
        </form>

        <div class="btn-group">
            <a class="btn btn-secondary" href="loveMusic.html">
                <i class="fas fa-heart"></i>喜欢列表
            </a>
            <a class="btn btn-primary" href="upload.html">
                <i class="fas fa-plus"></i>添加歌曲
            </a>
            <button id="delete" class="btn btn-danger">
                <i class="fas fa-trash"></i>删除选中
            </button>
        </div>
    </div>

    <table class="music-table">
        <thead>
        <tr>
            <th>选择</th>
            <th>歌名</th>
            <th>歌手</th>
            <th>播放</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="info" valign="middle">
        <!-- 音乐列表将通过JS动态加载 -->
        </tbody>
    </table>
</div>

<!-- 播放器容器 - 与代码1保持一致 -->
<div class="player-container">
    <!-- 最小化按钮 -->
    <button class="minimize-btn" id="minimizeBtn">
        <i class="fas fa-compress"></i>
    </button>

    <!-- 缩小状态图标 -->
    <div class="minimized-icon">
        <i class="fas fa-music"></i>
    </div>

    <div class="now-playing">正在播放: 暂无歌曲</div>

    <div class="progress-container">
        <div class="progress-info">
            <span class="current-time">00:00</span>
            <span class="duration">00:00</span>
        </div>
        <div class="progress-bar">
            <div class="progress-fill"></div>
            <div class="progress-handle"></div>
        </div>
    </div>

    <div class="player-controls">
        <button class="control-btn" id="stopBtn">
            <i class="fas fa-stop"></i>
        </button>
        <button class="control-btn play-pause-btn" id="playPauseBtn">
            <i class="fas fa-play" id="playPauseIcon"></i>
        </button>
    </div>
</div>
</body>
</html>
